package com.google.wave.poppy.controller;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONArray;
import org.json.JSONException;

import com.google.wave.api.Blip;
import com.google.wave.api.ElementType;
import com.google.wave.api.Event;
import com.google.wave.api.FormElement;
import com.google.wave.api.StyleType;
import com.google.wave.api.StyledText;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;
import com.google.wave.poppy.model.EmailStorage;


/**
 * A controller to add the email form to the wave and handle button click events
 * for the same.
 * 
 * @author prathapnirmal
 *
 */
public class EmailController {

	 /**
	  * The element id of the email input box.
	  */
	private static final String EMAIL_INPUT_ID = "email_input";
	
	/**
	 * Element id for the add email button.
	 */
	private static final String ADD_EMAIL_BUTTON_ID = "add_email_button";
	  
	/**
	 * Root blip in which the form will be rendered.
	 */
	private Wavelet wavelet;
	
	/**
	 * Email storage for this wavelet.
	 */
	private EmailStorage emailStorage;
	
	/**
	 * Logger for this class.
	 */
	private static final Logger LOG = Logger.getLogger(
			EmailController.class.getName());
	
	
	/**
	 * Constructor for controller.
	 * 
	 * @param rootBlip root blip on the wavelet.
	 */
	public EmailController(Wavelet wavelet) {
		this.wavelet = wavelet;
		this.emailStorage = new EmailStorage(wavelet);
	}
	
	/**
	 * Renders the email form on the blip.
	 */
	public void renderForm() {
		
		Blip blip = this.wavelet.getRootBlip();
		
	    // Clear out everything.
	    TextView document = blip.getDocument();
	    document.delete();

	    
	    // Set the title.
	    blip.getWavelet().setTitle(
	        new StyledText("Add Email Participants",
	            StyleType.HEADING3));

	    
	    // Insert the email input form.
	    document.append("\n");
	    document.append("Email: ");
	    document.appendElement(new FormElement(
	    		ElementType.INPUT,
	    		"Email:",
	    		EMAIL_INPUT_ID,
	        	""));

	    // Insert the update button.
	    document.append("\n");
	    document.appendElement(new FormElement(
	    		ElementType.BUTTON,
	    		ADD_EMAIL_BUTTON_ID,
	    		"Add"));
	    
	    // render the current participants email addresses.
	    document.append("\n");
	    document.appendElement(new FormElement(
		        ElementType.LABEL,
		        "current_participants_id",
		        "Current Participants:"));
	    
	    JSONArray participants = emailStorage.getEmailParticipants();
	    for (int i = 0; i < participants.length(); i++) {
	    	try {
				String emailAddress = participants.getString(i);
			    document.append("\n");
			    document.append(emailAddress);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	}
	
	/**
	 * Checks if the add button was clicked.
	 * 
	 * @param events is the list of events in the robot message bundle.
	 * @return true if the add button was clicked.
	 * 
	 */
	private boolean isAddButtonClicked(List<Event> events) {
		    return Util.isButtonClicked(events, ADD_EMAIL_BUTTON_ID);
	}
	
	/**
	 * Handles button click events for the email participants form.
	 * 
	 * @param events is the list of events in the robot message bundle.
	 */
	public void handleButtonClick(List<Event> events) {
		
		// handle add email button click event.
		if (isAddButtonClicked(events)) {
			Blip blip = this.wavelet.getRootBlip();
			String emailAddress = blip.getDocument().getFormView().
				getFormElement(EMAIL_INPUT_ID).getValue();
			
			if(Util.isValidEmailAddress(emailAddress)) {
				addEmailParticipant(emailAddress);			
			}
			
			// re-render the form after we add new participants.
			this.renderForm();
		}
	}

	/**
	 * Adds a new email participant to the wave and sends a welcome email to 
	 * the new participant.
	 * 
	 * @param emailAddress email address of the new participant.
	 * 
	 */
	private void addEmailParticipant(String emailAddress) {
		this.emailStorage.addEmailParticipant(emailAddress);
		LOG.log(Level.INFO, "valid email address added", emailAddress);
		
		//TODO: send welcome email.
	}
	
}
